package com.raylu.day06;

import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

// 将迟到数据发送到侧输出流
public class Example4OutputTag {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<String> result = env
                .addSource(new SourceFunction<String>() {
                    @Override
                    public void run(SourceContext<String> ctx) throws Exception {
                        ctx.collectWithTimestamp("hello", 1000L);
                        Thread.sleep(1000L);
                        ctx.emitWatermark(new Watermark(999L));
                        Thread.sleep(1000L);
                        ctx.collectWithTimestamp("hello", 2000L);
                        Thread.sleep(1000L);
                        ctx.emitWatermark(new Watermark(1999L));
                        Thread.sleep(1000L);
                        ctx.collectWithTimestamp("hello", 1000L);
                        Thread.sleep(1000L);
                    }

                    @Override
                    public void cancel() {

                    }
                })
                .keyBy(r -> r)
                .process(new KeyedProcessFunction<String, String, String>() {
                    @Override
                    public void processElement(String value, Context ctx, Collector<String> out) throws Exception {
                        if (ctx.timestamp() > ctx.timerService().currentWatermark()) {
                            out.collect("数据：" + value + "到达，时间戳是：" + ctx.timestamp() + "，" +
                                    "当前水位线是：" + ctx.timerService().currentWatermark() + "没有迟到");
                        } else {
                            ctx.output(
                                    // 单例
                                    // 泛型表示侧输出流中的元素类型
                                    new OutputTag<String>("late-event") {
                                    },
                                    "数据" + value + "到达，时间戳是：" + ctx.timestamp() + "，当前水位线是：" + ctx.timerService().currentWatermark() + "" +
                                            ", 迟到了"
                            );
                        }
                    }
                });


        result.print("主流：");

        result.getSideOutput(new OutputTag<String>("late-event"){}).print("侧输出流：");

        env.execute();
    }
}
